package net.mysoft.framework.authority;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.util.TokenHelper;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.util.LocalizedTextUtil;

/**
 * 
 * @author liuyang
 * 	防止表单重复提交的拦截器
 *	重写了struts2的tokenInterceptor
 *	前台jsp 没有token标签的不做拦截
 */
public class TokenInterceptor extends org.apache.struts2.interceptor.TokenInterceptor {
	private static final long serialVersionUID = -6680894220590585506L;  
	public static final String INVALID_TOKEN_CODE = "invalid.token";  

	protected String doIntercept(ActionInvocation invocation) throws Exception {
		String tokenName = TokenHelper.getTokenName();
		if(tokenName!=null){
			if (log.isDebugEnabled()) {
				log.debug("Intercepting invocation to check for valid transaction token.");  
			}  
			HttpSession session = ServletActionContext.getRequest().getSession(true);  
			synchronized (session) {
				//（1）判断Token是否有效  
				if (!TokenHelper.validToken()) {
				//（2）Token无效，返回结果invalid.token  
					//return handleInvalidToken(invocation);
					return null;
				}
			}  
		}
				//（3）Token有效时，去做更多的处理  
		return handleValidToken(invocation);
	}  

	protected String handleInvalidToken(ActionInvocation invocation) throws Exception {
		Object action = invocation.getAction();  
		String errorMessage = LocalizedTextUtil.findText(this.getClass(), "struts.messages.invalid.token",  
				invocation.getInvocationContext().getLocale(),  
				"The form has already been processed or no token was supplied, please try again.", new Object[0]);  
		if (action instanceof ValidationAware) {  
			((ValidationAware) action).addActionError(errorMessage);  
		} else {  
			log.warn(errorMessage);  
		}  
		return INVALID_TOKEN_CODE;  
	}  

	protected String handleValidToken(ActionInvocation invocation) throws Exception {  
		return invocation.invoke();  
	}  

}